int buzzerPin = A0;
int firePin = 2;
int humanPin = 3;
int fireAlarm = 0, humanAlarm = 0;

#define D0 -1
#define D1 262
#define D2 293
#define D3 329
#define D4 349
#define D5 392
#define D6 440
#define D7 494
#define M1 523
#define M2 586
#define M3 658
#define M4 697
#define M5 783
#define M6 879
#define M7 987
#define H1 1045
#define H2 1171
#define H3 1316
#define H4 1393
#define H5 1563
#define H6 1755
#define H7 1971
//列出全部D调的频率
#define WHOLE 1
#define HALF 0.5
#define QUARTER 0.25
#define EIGHTH 0.25
#define SIXTEENTH 0.625
//列出所有节拍
int tune[]=        //根据简谱列出各频率
{
  M3,M3,M4,M5,
  M5,M4,M3,M2,
  M1,M1,M2,M3,
  M3,M2,M2,
  M3,M3,M4,M5,
  M5,M4,M3,M2,
  M1,M1,M2,M3,
  M2,M1,M1,
  M2,M2,M3,M1,
  M2,M3,M4,M3,M1,
  M2,M3,M4,M3,M2,
  M1,M2,D5,D0,
  M3,M3,M4,M5,
  M5,M4,M3,M4,M2,
  M1,M1,M2,M3,
  M2,M1,M1
};
float durt[]=       //根据简谱列出各节拍
{
  1,1,1,1,
  1,1,1,1,
  1,1,1,1,
  1+0.5,0.5,1+1,
  1,1,1,1,
  1,1,1,1,
  1,1,1,1,
  1+0.5,0.5,1+1,
  1,1,1,1,
  1,0.5,0.5,1,1,
  1,0.5,0.5,1,1,
  1,1,1,1,
  1,1,1,1,
  1,1,1,0.5,0.5,
  1,1,1,1,
  1+0.5,0.5,1+1,
};
int length;

void setup() {
  delay(5000);
  pinMode(buzzerPin, OUTPUT);
  pinMode(firePin,INPUT);
  pinMode(humanPin,INPUT);
  length = sizeof(tune)/sizeof(tune[0]);   //计算长度
  Serial.begin(9600);
}

void loop() {
  unsigned char i, j;
  if(isTriggered())
  {
    Serial.println("on");
  }
  else Serial.println("off");
  fireAlarm = digitalRead(firePin);
  humanAlarm = digitalRead(humanPin);
  while(fireAlarm == 1)
  {
    Serial.println("while loop 1");
    for(i = 0; i < 80; i++)
    {
      digitalWrite(buzzerPin, HIGH);
      delay(1);
      digitalWrite(buzzerPin, LOW);
      delay(1);
    }
    for(j = 0; j < 100; j++)
    {
      digitalWrite(buzzerPin, HIGH);
      delay(2);
      digitalWrite(buzzerPin, LOW);
      delay(2);
    }
    fireAlarm = digitalRead(firePin);
  }
  while(humanAlarm == 1)
  {
    Serial.println("while loop 2");
    for(int x = 0; x < length; x++)
    {
      tone(buzzerPin, tune[x]);
      delay(500 * durt[x]);   //这里用来根据节拍调节延时，500这个指数可以自己调整，在该音乐中，我发现用500比较合适。
      noTone(buzzerPin);
      humanAlarm = digitalRead(humanPin);
      if (humanAlarm == 0)
      {
        Serial.println("break while loop 2");
        break;
      }
    }
  }
} 
 
boolean isTriggered()
{
    if(!digitalRead(humanPin))
    {
        delay(50);
        if(!digitalRead(humanPin))
        return true;//the collision sensor triggers
    }
    return false;
}
